package com.itheima.controller;

import com.itheima.pojo.Book;
import com.itheima.service.BookService;
import com.itheima.vo.Code;
import com.itheima.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author by itheima
 * @Date 2022/4/27
 * @Description 定义book的控制器类
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService service;

    //restful的post表示新增
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean result = service.save(book);
        Integer code = result? Code.SAVE_OK : Code.SAVE_ERR;
        String message = result? "保存成功" : "保存失败";
        // {"code" : 20011, "data" : true,"message" : "保存成功"}
        // {"code" : 20010, "data" : false,"message" : "保存失败"}
        return new Result(code,result,message);
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        boolean result = service.update(book);
        Integer code = result? Code.UPDATE_OK : Code.UPDATE_ERR;
        String message = result? "修改成功" : "修改失败";
        return new Result(code,result,message);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean result = service.delete(id);
        Integer code = result? Code.DELETE_OK : Code.DELETE_ERR;
        String message = result? "删除成功" : "删除失败";
        return new Result(code,result,message);
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = service.getById(id);
        Integer code = book != null? Code.GET_OK : Code.GET_ERR;
        String message = book != null? "查询单个成功" : "查询单个失败";
        return new Result(code,book,message);
    }

    @GetMapping
    public Result getAll(){
//        int a=10/0;//模拟异常
        List<Book> list = service.getAll();
        Integer code = list != null && list.size() != 0? Code.GET_OK : Code.GET_ERR;
        String message = list != null && list.size() != 0? "查询全部成功" : "查询全部失败";
        return new Result(code,list,message);
    }
}
